<!-- src/views/AddressManage.vue -->
<template>
  <div class="address-manage">
    <div class="address-list">
      <h3>收货地址</h3>
      <el-button type="primary" @click="addAddress" style="margin-bottom: 10px"
        >新增地址</el-button
      >
      <div
        v-for="address in addressList"
        :key="address.id"
        class="address-item"
      >
        <div class="address-info">
          <div class="address-header">
            <span v-if="address.isDefault === 1" class="default-tag"
              >默认地址</span
            >
            <div class="address-details">
              <div class="detail-row">
                <label>收货人姓名：</label>
                <span class="address-name">{{ address.addressName }}</span>
              </div>
              <div class="detail-row">
                <label>配送区域：</label>
                <span>{{ address.address }}</span>
              </div>
              <div class="detail-row">
                <label>详细地址：</label>
                <span>{{ address.detail }}</span>
              </div>
              <div class="detail-row">
                <label>手机：</label>
                <span>{{ address.mobile }}</span>
              </div>
              <div class="detail-row">
                <label>备注：</label>
                <span>{{ address.remark }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="address-actions">
          <el-button type="text" @click="setAsDefault(address)"
            >设为默认</el-button
          >
          <el-button type="text" @click="editAddress(address)">编辑</el-button>
          <el-button type="text" @click="deleteAddress(address)"
            >删除</el-button
          >
        </div>
      </div>
    </div>

    <!-- 添加/编辑地址对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        :model="addressForm"
        :rules="rules"
        ref="addressForm"
        label-width="100px"
      >
        <el-form-item label="配送地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="请选择省市区"
            @change="handleRegionChange"
            :show-all-levels="false"
            :popper-class="'custom-cascader'"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="已选地址">
          <span>{{ displayAddress }}</span>
        </el-form-item>

        <el-form-item prop="userId" v-show="false">
          <el-input v-model="userId" type="hidden"></el-input>
        </el-form-item>
<!--         <el-form-item prop="id" v-show="false">
          <el-input v-model="id" type="hidden"></el-input>
        </el-form-item> -->

        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.detail"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>

        <el-form-item label="收货人姓名" prop="addressName">
          <el-input
            v-model="addressForm.addressName"
            placeholder="请输入收货人姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="addressForm.mobile"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addressForm.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item label="是否默认" prop="isDefault">
          <el-radio-group v-model="addressForm.isDefault">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addressForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import areaData from "@/assets/area_format_object.json";
function convertToCascaderFormat(data) {
  const result = [];

  for (const [code, info] of Object.entries(data)) {
    const province = {
      value: code,
      label: info.n,
      children: [],
    };

    if (info.c) {
      for (const [cityCode, cityInfo] of Object.entries(info.c)) {
        const city = {
          value: cityCode,
          label: cityInfo.n,
          children: [],
        };

        if (cityInfo.c) {
          // 遍历区县
          for (const [districtCode, districtInfo] of Object.entries(
            cityInfo.c
          )) {
            city.children.push({
              value: districtCode,
              label: districtInfo.n,
            });
          }
        }

        province.children.push(city);
      }
    }

    result.push(province);
  }

  return result;
}
export default {
  name: "AddressManage",
  data() {
    return {
      addressList: [],
      dialogVisible: false,
      dialogTitle: "",
      userId: "",
      addressForm: {
        id: "",
        userId: "",
        addressName: "",
        mobile: "",
        detail: "",
        address: "",
        remark: "",
        isDefault: "0",
        region: [],
        province: "",
        city: "",
        district: "",
      },
      rules: {
        addressName: [
          { required: true, message: "请输入收货人姓名", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        detail: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        region: [
          { required: true, message: "请选择配送地区", trigger: "change" },
        ],
      },
      regionOptions: [],
    };
  },
  computed: {
    displayAddress() {
      const region = this.addressForm.region;
      if (!region || region.length < 3) return "";

      // 获取省、市、区的 label
      const provinceLabel = this.getRegionLabel(region[0], this.regionOptions);
      const cityLabel = this.getRegionLabel(region[1], this.regionOptions);
      const districtLabel = this.getRegionLabel(region[2], this.regionOptions);

      // 如果省和市相同（直辖市），则合并
      return provinceLabel === cityLabel
        ? `${provinceLabel} / ${districtLabel}`
        : `${provinceLabel} / ${cityLabel} / ${districtLabel}`;
    },
  },

  created() {
    let loginName = sessionStorage.getItem("loginName");
    if(!loginName) {
      this.$message.error("权限不足，将回到首页！")
      this.$router.push({
        name: 'IndexCenter'
      })
      return;
    }
    this.getUserId();
    this.loadRegionData();
  },
  methods: {
    // 加载地址列表
    async loadAddressList() {
      try {
        const response = await this.$http.post("/api/address/list", {
          userId: this.userId,
        });
        this.addressList = response.data;

        // 如果后端返回的是数组，直接使用；如果是对象，需要处理
        if (Array.isArray(this.addressList)) {
          // 确保每个地址都有必要的字段
          this.addressList.forEach((address) => {
            if (!address.province) address.province = "";
            if (!address.city) address.city = "";
            if (!address.district) address.district = "";
            if (!address.mobile) address.mobile = "";
            if (!address.isDefault) address.isDefault = 0;
          });
        }
      } catch (error) {
        this.$message.error("加载地址失败：" + error.message);
      }
    },

    getUserId() {
      this.$http
        .post(
          "/api/address/getUserId",
          "token=" + sessionStorage.getItem("token")
        )
        .then((res) => {
          this.userId = res.data.userId;
          this.loadAddressList();
          this.addressForm.userId = this.userId;
        });
    },

    // 加载地区数据
    async loadRegionData() {
      try {
        // 使用本地 JSON 文件
        const data = areaData; // 直接使用导入的 areaData
        this.regionOptions = convertToCascaderFormat(data);
        console.log("地区数据加载成功:", this.regionOptions);
      } catch (error) {
        console.error("加载地区数据失败:", error);
        this.$message.error("加载地区数据失败：" + error.message);
      }
    },
    getRegionLabel(code, options) {
      for (const item of options) {
        if (item.value === code) {
          return item.label;
        }
        if (item.children && item.children.length > 0) {
          const result = this.getRegionLabel(code, item.children);
          if (result) return result;
        }
      }
      return "";
    },

    // 添加新地址
    addAddress() {
      this.dialogTitle = "新增地址";
      this.resetForm();
      this.dialogVisible = true;
    },

    // 编辑地址
    editAddress(address) {
      this.dialogTitle = "修改地址";
      this.addressForm = { ...address };
      const provinceCode = this.findRegionCode(
        address.province,
        this.regionOptions
      );
      const cityCode = this.findRegionCode(address.city, this.regionOptions);
      const districtCode = this.findRegionCode(
        address.district,
        this.regionOptions
      );
      this.addressForm.region = [provinceCode, cityCode, districtCode].filter(
        (code) => code
      );
      this.dialogVisible = true;
    },

    findRegionCode(name, options) {
      for (const item of options) {
        if (item.label === name) {
          return item.value;
        }
        if (item.children && item.children.length > 0) {
          const code = this.findRegionCode(name, item.children);
          if (code) {
            return code;
          }
        }
      }
      return "";
    },

    // 设置为默认地址
    async setAsDefault(address) {
      try {
        await this.$http.post(`/api/address/set-default`, {
          userId: this.userId,
          id: address.id,
        });
        this.$message.success("设置成功");
        this.loadAddressList();
      } catch (error) {
        this.$message.error("设置失败：" + error.message);
      }
    },

    // 删除地址（逻辑删除）
    async deleteAddress(address) {
      try {
        await this.$http.post(`/api/address/delete`, {
          id: address.id,
        });
        this.$message.success("删除成功");
        this.loadAddressList();
      } catch (error) {
        this.$message.error("删除失败：" + error.message);
      }
    },

    // 处理地区选择变化
    handleRegionChange(value) {
      if (value && value.length >= 3) {
        const provinceLabel = this.getRegionLabel(value[0], this.regionOptions);
        const cityLabel = this.getRegionLabel(value[1], this.regionOptions);
        const districtLabel = this.getRegionLabel(value[2], this.regionOptions);

        this.addressForm.province = provinceLabel;
        this.addressForm.city = cityLabel;
        this.addressForm.district = districtLabel;
      } else if (value && value.length === 2) {
        const provinceLabel = this.getRegionLabel(value[0], this.regionOptions);
        const districtLabel = this.getRegionLabel(value[1], this.regionOptions);

        this.addressForm.province = provinceLabel;
        this.addressForm.city = provinceLabel; // 直辖市
        this.addressForm.district = districtLabel;
      }
    },

    //     if (value && value.length >= 3) {
    //       this.addressForm.province = value[0]
    //       this.addressForm.city = value[1]
    //       this.addressForm.district = value[2]
    //     }else if (value && value.length === 2) {
    //   // 如果只有两级（如直辖市），则 city 和 province 相同
    //   this.addressForm.province = value[0]
    //   this.addressForm.city = value[0] // 省和市相同
    //   this.addressForm.district = value[1]
    // }

    //
    resetForm() {
      if (this.$refs["addressForm"]) {
        this.$refs["addressForm"].resetFields();
      }
      this.addressForm = {
        id: "",
        addressName: "",
        mobile: "",
        detail: "",
        address: "",
        remark: "",
        isDefault: "0",
        region: [],
        province: "",
        city: "",
        district: "",
      };
    },

    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            // 拼接完整地址
            const fullAddress = `${this.addressForm.province} ${this.addressForm.city} ${this.addressForm.district} ${this.addressForm.detail}`;
            this.addressForm.address = fullAddress;

            if (this.addressForm.id) {
              await this.$http.post(`/api/address/update`, {
                ...this.addressForm,
                userId: this.userId,
              });
            } else {
              await this.$http.post("/api/address/add", {
                ...this.addressForm, 
                userId: this.userId,
              }).then(rs => {
                console.log("add address: ", rs)
                if(rs.data == false) {
                  this.$message.error("用户地址已达上限");
                }
              });
            }

            // this.$message.success("操作成功");
            this.dialogVisible = false;
            this.loadAddressList();
          } catch (error) {
            this.$message.error("操作失败：" + error.message);
          }
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
  },

};
</script>

<style scoped>
.address-manage {
  padding: 20px;
}

.address-list {
  width: 75%;
  float: right;
  margin-bottom: 20px;
  /* 为收货地址整体区域设置白色背景 */
  background-color: #fff;
  padding: 10px; /* 可根据需要调整内边距 */
  border-radius: 4px; /* 可选，添加圆角让样式更美观 */
}

.address-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background-color: #fff;
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
}

.default-tag {
  background-color: #f0f9ff;
  color: #409eff;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  margin-right: 10px;
}

.address-details {
  display: flex;
  flex-direction: column;
}

.detail-row {
  display: flex;
  margin-bottom: 5px;
}

.detail-row label {
  font-weight: bold;
  margin-right: 5px;
}

.address-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.address-actions .el-button {
  margin-bottom: 5px;
}

.dialog-footer {
  text-align: right;
}

/* 重点：限制 cascader 下拉框高度 */
.el-cascader-menu {
  max-height: 300px !important;
  overflow-y: auto !important;
  border-radius: 4px;
}

.el-cascader-node {
  padding: 6px 10px;
  font-size: 14px;
}
</style>